package com.yilin.platform.base_core.components.minio;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yilin.platform.base_core.application.AppUtil;
import com.yilin.platform.base_core.commons.exception.BusinessException;
import com.yilin.platform.base_core.commons.utils.ImageEditUtils;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.Date;

/**
 * 上传文件处理工具
 * */
public class FileDealUtil {
    //允许的图片格式
    private static final String UPLOAD_IMAGE_EXTS = ".jpg/.jpeg/.png/.gif";
    //图片最大限制 单位B
    private static final long UPLOAD_IMAGE_MAX_SIZE_B = 10 * 1024 * 1024L;
    //服务器临时公共文件夹
    private static final String UPLOAD_COMMON_PATH = "common";

    /**
     * 压缩图片到工程文件夹
     */
    public static File compressImgToProFile(MultipartFile multiFile, String rootDir) {
        String ext = FilenameUtils.getExtension(multiFile.getOriginalFilename());
        if (StringUtil.isEmpty(ext)) ext = "jpg";
        File fromFile = saveTempFile(multiFile, rootDir);
        //创建工程文件夹
        File toFile = createTempFile(rootDir, ext);
        ImageEditUtils.compressPic(fromFile, toFile, 1000, 1000);
        return toFile;
    }

    /**
     * 保存图片到临时文件夹
     */
    public static File saveTempFile(MultipartFile multiFile, String rootDir) {
       return saveTempFile( multiFile,  rootDir,  true);
    }

    public static File saveTempFile(MultipartFile multiFile, String rootDir, boolean isImg) {
        try {
            // 判断格式
            String ext = FilenameUtils.getExtension(multiFile.getOriginalFilename());
            if (StringUtil.isEmpty(ext)) ext = isImg ? "jpg" : "";
            // 将文件后缀转成小写
            if (StringUtils.isNotBlank(ext)) {
                ext = ext.toLowerCase();
            }
            //创建临时文件夹
            File fromFile = createTempFile(rootDir, ext);
            multiFile.transferTo(fromFile);
            return fromFile;
        } catch (IOException e) {
            throw new BusinessException("上传失败，请重新上传");
        }
    }

    /**
     * 创建文件夹
     */
    public static File createTempFile(String rootDir, String ext) {
        //今天日期
        String today = DateFormatUtils.format(new Date(), "yyyyMMdd");
        //次级文件路径
        StringBuilder imgPath = new StringBuilder("//temporary").append("//")
                .append(UPLOAD_COMMON_PATH).append("//")
                .append(today).append("//");
        //如果文件夹不存在，创建文件夹
        File dest = new File(rootDir + imgPath);
        if (!dest.exists()) {
            boolean mkdirs = dest.mkdirs();
            if (!mkdirs) throw new BusinessException("创建文件夹失败");
        }
        //返回文件夹及次级路径
        String path = rootDir + imgPath.toString() + AppUtil.getUUID() + "." + ext;
        return new File(path);
    }

    /**
     * file 回转tMultipart
     */
    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
        return new CommonsMultipartFile(item);
    }


    /**
     * file 回转tMultipart
     */
    public static String splitRex(String path) {
        if (path.contains("?")){
          return  path.split("\\?")[0];
        }
        return path;
    }


    /**
     * 删除文件夹
     * */
    public static Boolean deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                //递归删除目录下的文件
                deleteFile(f);
            } else {
                //文件删除
                f.delete();
                //打印文件名
                System.out.println("文件名：" + f.getName());
            }
        }
        //文件夹删除
        file.delete();
        System.out.println("目录名：" + file.getName());
        return true;
    }

}
